<?php
declare (strict_types=1);

namespace app\api\controller;

use app\common\model\Area;
use app\common\model\Bank;
use app\common\model\Business as BusinessModel;
use app\common\model\BusinessCensus;
use app\common\model\BusinessDraw;
use app\common\model\BusinessFundsFlow;
use app\common\model\BusinessVideoApply;
use app\common\model\Config;
use app\common\model\ProductCate;
use app\common\model\UserBusinessView;
use app\common\model\UserCollectProduct;
use app\common\tool\Result;
use think\exception\ValidateException;
use think\facade\Event;
use think\Response;

class Business extends Base
{

    /**
     * @return Response
     * 原点 2022年12月23日10:53:03 商家中心首页
     */
    public function index(): Response
    {
        try {
            $result['business'] = [
                'id'     => $this->business->id,
                'title'  => $this->business->title,
                'logo'   => $this->business->logo,
                'cover'  => $this->business->cover,
                'mobile' => substr_replace($this->business->mobile, '****', 3, 4),
                'type'   => $this->business->type,
                'video_status' => $this->business->video_status
            ];
            $census = BusinessCensus::getCensus($this->business->id, 'order_income,order_count');

            $where = ['business_id'=>$this->business->id, 'is_del'=>0];
            $result['census'] = [
                'today_income'  => $census ? $census->order_income : '0.00',
                'sum_income'    => $this->business->sum_order_income,
                'fans'          => $this->business->fans,
                'today_visitor' => UserBusinessView::where($where)->whereDay('create_time')->count(),
                'collect'       => UserCollectProduct::where($where)->count(),
                'today_order'   => $census ? $census->order_count : 0,
                'sum_order'     => $this->business->sum_order_count,
                'recorded'      => $this->business->recorded,
                'not_recorded'  => $this->business->not_recorded,
            ];
            return Result::success('success', $result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2023年1月11日15:21:22 统计页面
     */
    public function census(): Response
    {
        try {
            $result = BusinessCensus::getCommonCensus($this->business, $this->request->get());
            return Result::success('success', $result);
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @return Response
     * 原点 2022年12月23日11:10:25 店铺资料
     */
    public function read(): Response
    {
        $this->business->bank_list = Bank::where(['is_del' => 0, 'status' => 1])->field('id,title')->select();

        return Result::success('success', $this->business);
    }

    /**
     * @return Response
     * 原点 2022年12月23日13:47:25 保存修改的资料
     */
    public function save(): Response
    {
        try {
            $param = $this->request->post('', '', $this->filter);
            $v = validate('Business');
            if (!$v->scene($param['type'])->check($param)) {
                return Result::fail($v->getError());
            }
            if (isset($param['district_id']) && $param['district_id']) {
                $address = Area::where('code', $param['district_id'])->find();
                if (empty($address)) {
                    return Result::fail('店铺地址错误！');
                }
                $param['full_address'] = $address->province . $address->city . $address->district . $param['address_details'];
            }
            if (isset($param['return_district_id']) && $param['return_district_id']) {
                $address = Area::where('code', $param['return_district_id'])->find();
                if (empty($address)) {
                    return Result::fail('退货地址错误！');
                }
                $param['return_full_address'] = $address->province . $address->city . $address->district . $param['return_address_details'];
            }
            unset($param['type']);
            BusinessModel::update($param, ['id' => $this->business->id]);
            return Result::success('保存成功');
        } catch (\Exception $e) {
            return Result::fail($e->getMessage());
        }
    }

    /**
     * @param $pid - 父级ID，默认0
     * @return Response
     * 原点 2022年12月24日09:32:20 获取商家允许的经营类目，一级分类
     */
    public function getCate($pid): Response
    {
        if (!$pid) {
            $data = ProductCate::whereIn('id', $this->business->cate_1)
                ->where(['is_del' => 0, 'status' => 1])->field('id,title')->select();
        } else {
            $data = ProductCate::getCate($pid);
        }
        return Result::success('success', $data);
    }

    /**
     * 提现页面
     * @return Response
     */
    public function draw(): Response
    {
        $bank = $this->business->bank_name . "(".substr($this->business->bank_number, -4).")";
        $money = $this->business->draw;
        $msg = Config::where('name', 'business_draw_msg')->value('value');

        $data = [
            'bank' => $bank,
            'money' => $money,
            'msg' => handleRichText($msg)
        ];

        $result = ['code'=>1, 'msg'=>'success', 'data'=>$data];

        return Result::fastReturn($result);
    }

    /**
     * 提现申请
     * @return Response
     */
    public function drawApply(): Response
    {
        $param = $this->request->post('', '', $this->filter);
        try {
            $this->validate($param, 'BusinessDraw');
        } catch (ValidateException $e) {
            return Result::fail($e->getError());
        }

        $this->business->pay_password = $this->user->pay_password;
        return Result::fastReturn(BusinessDraw::add($param, $this->business, $this->system));
    }

    /**
     * 提现记录
     * @return Response
     */
    public function drawRecord(): Response
    {
        $map['business_id'] = $this->business->id;
        $list = BusinessDraw::getPageList($map, 'id,create_time,status,money,amount,cost', $this->getPage(),$this->getLimit(), false);

        return Result::fastReturn($list);
    }

    /**
     * 资金流水
     * @return Response
     */
    public function fundsFlow(): Response
    {
        $status = $this->request->get('status', 2);
        $month = $this->request->get('month','');
        $day = $this->request->get('day','');
        $listRows = [
            'page' => $this->getPage(),
            'list_rows' => $this->getLimit()
        ];
        $list = BusinessFundsFlow::where(['business_id' => $this->business->id, 'status'=>$status]);
        if($month) $list->whereMonth('create_time', $month);
        if($day) $list->whereDay('create_time', $day);

        $list = $list->field('id,type,create_time,status,amount,real_amount')->order('create_time', 'desc')->paginate($listRows);

        $result = ['code'=>1, 'msg'=>'success', 'data'=>$list->items()];
        return Result::fastReturn($result);
    }

    /**
     * 流水详情
     * @return Response
     */
    public function fundsInfo(int $id): Response
    {
        $info = BusinessFundsFlow::where('id', $id)->field('id,order_sn,type,create_time,deal_time,entry_time,status,amount,real_amount,sku_list')->find();
        $info['balance'] = $this->business->draw;

        $result = ['code'=>1, 'msg'=>'success', 'data'=>$info];
        return Result::fastReturn($result);
    }

    /**
     * 视频上传申请
     * @return Response
     */
    public function videoApply(): Response
    {
        return Result::fastReturn(BusinessVideoApply::add($this->business));
    }
}

